package com.neidetcher.toolkit.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class Timer
{
   private Long startTime = null;
   private Long stopTime = null;
   private String operationName = "Thread (" + Thread.currentThread().getName() + ")";
   
   private Log log = LogFactory.getLog(Timer.class);

   
   public Timer()
   {
      start();
   }
   
   public Timer(String operationNameIn)
   {
      operationName = operationNameIn;
      start();
   }
   
   public void start()
   {
      log.info("start timer " + operationName);
      startTime = System.currentTimeMillis();
   }

   /** returns milliseconds */
   public Long stop()
   {
      stopTime = System.currentTimeMillis();
      log.info("stop timer " + operationName + ": took " + howLong() + " ms");
      return howLong();
   }

   /** returns milliseconds */
   public Long howLong()
   {
      if (stopTime != null)
      {
         return stopTime - startTime;
      }
      return System.currentTimeMillis() - startTime;
   }

   public String toString()
   {
      if (stopTime != null)
      {
         return "not stopped " + operationName + " currently took " + howLong() + " milliseconds";
      }
      return operationName + " took " + howLong() + " milliseconds";
   }
}
